package vaccine.appointment.system.inventory.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import vaccine.appointment.system.common.annotation.AutoWrapResult;
import vaccine.appointment.system.common.annotation.RequireRole;
import vaccine.appointment.system.inventory.dataobject.Inventory;
import vaccine.appointment.system.inventory.service.InventoryService;
import vaccine.appointment.system.inventory.vo.AddInventoryRequest;
import vaccine.appointment.system.inventory.vo.InventoryVO;
import vaccine.appointment.system.inventory.vo.LowStockAlertVO;
import vaccine.appointment.system.inventory.vo.UpdateInventoryRequest;
import vaccine.appointment.system.user.dataobject.User;
import vaccine.appointment.system.user.enums.IdentityInfoEnum;
import vaccine.appointment.system.user.mapper.UserMapper;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * 管理员库存控制器
 */
@AutoWrapResult
@RequestMapping("/admin/inventory")
@RestController
@RequireRole({IdentityInfoEnum.HOSPITAL_ADMIN, IdentityInfoEnum.SUPER_ADMIN})
public class AdminInventoryController {

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 添加库存记录
     * @param request 添加库存请求
     * @param httpRequest HTTP请求
     * @return 是否成功
     */
    @PostMapping("")
    public Boolean addInventory(@Valid @RequestBody AddInventoryRequest request, HttpServletRequest httpRequest) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        return inventoryService.addInventory(request, userId);
    }

    /**
     * 更新库存数量
     * @param inventoryId 库存ID
     * @param request 更新库存请求
     * @param httpRequest HTTP请求
     * @return 是否成功
     */
    @PutMapping("/{inventoryId}")
    public Boolean updateInventory(
            @PathVariable Integer inventoryId,
            @Valid @RequestBody UpdateInventoryRequest request,
            HttpServletRequest httpRequest) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        return inventoryService.updateInventoryCount(inventoryId, request.getChangeCount(), userId);
    }

    /**
     * 查询库存列表
     * @param httpRequest HTTP请求
     * @return 库存列表
     */
    @GetMapping("/list")
    public List<InventoryVO> getInventoryList(HttpServletRequest httpRequest) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        User user = userMapper.selectById(userId);
        
        // 如果是接种点管理员，只能查看自己接种点的库存
        Integer vaccinationSiteId = null;
        if (user.getIdentityInfo().equals(IdentityInfoEnum.HOSPITAL_ADMIN.getCode())) {
            vaccinationSiteId = user.getVaccinationSiteId();
        }
        
        return inventoryService.getInventoryList(vaccinationSiteId);
    }

    /**
     * 查询低库存预警列表
     * @param threshold 库存阈值（可选，默认10）
     * @param httpRequest HTTP请求
     * @return 低库存预警列表
     */
    @GetMapping("/low-stock-alert")
    public List<LowStockAlertVO> getLowStockAlerts(
            @RequestParam(required = false) Integer threshold,
            HttpServletRequest httpRequest) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        User user = userMapper.selectById(userId);
        
        // 如果是接种点管理员，只能查看自己接种点的预警
        Integer vaccinationSiteId = null;
        if (user.getIdentityInfo().equals(IdentityInfoEnum.HOSPITAL_ADMIN.getCode())) {
            vaccinationSiteId = user.getVaccinationSiteId();
        }
        
        return inventoryService.getLowStockAlerts(vaccinationSiteId, threshold);
    }

    /**
     * 删除库存记录（逻辑删除）
     * 说明：删除库存只是删除该疫苗在某个接种点的库存记录，疫苗本身不会被删除
     * 数据库中的数据不会物理删除，只是标记为已删除（del_flg=1）
     * 
     * @param inventoryId 库存ID
     * @param httpRequest HTTP请求
     * @return 是否成功
     */
    @DeleteMapping("/{inventoryId}")
    public Boolean deleteInventory(
            @PathVariable Integer inventoryId,
            HttpServletRequest httpRequest) {
        Integer userId = (Integer) httpRequest.getAttribute("userId");
        User user = userMapper.selectById(userId);
        
        // 获取库存记录
        Inventory inventory = inventoryService.selectById(inventoryId);
        if (inventory == null) {
            throw new vaccine.appointment.system.common.exception.CommonException(
                vaccine.appointment.system.common.errorcode.CommonErrorCode.NOT_FOUND);
        }
        
        // 权限检查：接种点管理员只能删除自己接种点的库存
        if (user.getIdentityInfo().equals(IdentityInfoEnum.HOSPITAL_ADMIN.getCode())) {
            Integer userSiteId = user.getVaccinationSiteId();
            // 特殊情况：如果库存记录的vaccine_id为null（无效数据），允许删除
            if (inventory.getVaccineId() == null) {
                // 无效库存记录，允许删除（用于清理脏数据）
            } else if (userSiteId == null) {
                // 有效库存记录，但用户没有关联接种点，不允许删除
                throw new vaccine.appointment.system.common.exception.CommonException(
                    vaccine.appointment.system.common.errorcode.CommonErrorCode.FORBIDDEN);
            } else if (!inventory.getVaccinationSiteId().equals(userSiteId)) {
                // 库存记录不属于该用户的接种点，不允许删除
                throw new vaccine.appointment.system.common.exception.CommonException(
                    vaccine.appointment.system.common.errorcode.CommonErrorCode.FORBIDDEN);
            }
        }
        // 超级管理员可以删除任何库存
        
        // 执行逻辑删除（设置del_flg=1）
        return inventoryService.delete(inventoryId);
    }
}

